import React from "react";
import { connect } from "dva";
import { Button, message, Popconfirm, Modal } from "antd";
import {
  UrlConfig,
  weixinPush,
  validateSensitive,
  transcode


} from "../../../services/fetch";
import {
  addInformation
} from "../../../services/theme";
import { throttle } from "../../../utils/Date";
import "./Video.scss";
import "./Right.scss";
import "./Footer.scss";

let adding = false;
const { confirm } = Modal;
/**
 * 连续点击判断
 */
const getAdding = () => {
  return adding;
};
const setAdding = (val, time) => {
  if (time > 0) {
    setTimeout(() => {
      window.close();
      adding = val;
    }, time);
  } else {
    adding = val;
  }
};
const getCookie = cookie_name => {
  var allcookies = document.cookie;
  //索引长度，开始索引的位置
  var cookie_pos = allcookies.indexOf(cookie_name);

  // 如果找到了索引，就代表cookie存在,否则不存在
  if (cookie_pos != -1) {
    // 把cookie_pos放在值的开始，只要给值加1即可
    //计算取cookie值得开始索引，加的1为“=”
    cookie_pos = cookie_pos + cookie_name.length + 1;
    //计算取cookie值得结束索引
    var cookie_end = allcookies.indexOf(";", cookie_pos);

    if (cookie_end == -1) {
      cookie_end = allcookies.length;
    }
    //得到想要的cookie的值
    var value = unescape(allcookies.substring(cookie_pos, cookie_end));
  }
  return value;
};

@connect(({ add, video, theme }) => ({
  add: add,
  video: video,
  theme: theme
}))
export default class Footer extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      adding: false,
      user_name: "",
      add_information_id: 0
    };
  }

  componentDidMount() {
    // console.log(getCookie('user_name'));
    let username = "";
    // if (getCookie('user_name')){
    //     username = getCookie('user_name');
    //     this.setState({
    //         user_name: getCookie('user_name')
    //     });
    // }else{
    let userinfo = localStorage.getItem("userInfo");
    //编辑名称默认为登陆管理员
    if (userinfo) {
      if (typeof userinfo === "string") {
        userinfo = JSON.parse(userinfo);
      }
      username = userinfo.user_name;
      this.setState({
        user_name: username
      });
    }

    // }

    if (!username && window.location.host.indexOf("localhost") <= -1) {
      message.error("登陆已过期，请重新登陆~");
      setTimeout(() => {
        if (window.top) {
          window.top.location.href = UrlConfig;
        } else {
          window.location.href = UrlConfig;
        }
      }, 2000);
      return;
    }
  }
  /**
   * 表单重置
   */
  reSet = () => {
    this.props.reset();
  };

  confirm = () => {
    window.close();
  };

  /**
   * 提交审核 保存草稿
   */
  submitForm = idss => {
    let token = localStorage.getItem("token");
    let leftForm = this.props.getLeft();
    let rightForm = this.props.getRight();
    let allForm = {};

    console.log(leftForm, rightForm);
    if (leftForm && rightForm) {
      Object.assign(allForm, leftForm, rightForm);

      if (this.state.add_information_id > 0) {
        if (idss > 0) {
          this.toShenHe();
        } else {
          this.editSave();
        }
        return;
      }
      if (getAdding()) {
        return false;
      }
      setAdding(true, 0);
      allForm.user_name = this.state.user_name;
      allForm.token = token;
      let _that = this;
      if (this.props.add.configJson.sensitivewordsSwitch) {
        validateSensitive({ content: allForm["content"] }).then(res => {
          if (res.data.code === 500) {
            confirm({
              title: "存在敏感词，确认继续保存吗",
              content: "敏感词：" + res.data.data,
              onOk() {
                _that.props.dispatch({
                  type: "add/addInformation",
                  data: allForm,
                  callback: data => {
                    // this.closeWindow();
                    setAdding(false, 0);
                    if (data.code === 200) {
                      this.submitTranscode(
                        this.props.add.transcode_data,
                        data.data,
                        2
                      );
                      message.success("保存成功!");
                      _that.setState({
                        add_information_id: data.data
                      });

                      if (idss === 1) {
                        _that.props.dispatch({
                          type: "add/getAuditVideo",
                          data: {
                            status: 1,
                            information_ids: [data.data]
                          }
                        });
                        _that.closeWindow();
                      }
                    }
                  }
                });
              },
              onCancel() {
                setAdding(false, 0);
              }
            });
          } else {
            _that.props.dispatch({
              type: "add/addInformation",
              data: allForm,
              callback: data => {
                // this.closeWindow();
                setAdding(false, 0);
                if (data.code === 200) {
                  this.submitTranscode(
                    this.props.add.transcode_data,
                    data.data,
                    2
                  );
                  message.success("保存成功!");
                  _that.setState({
                    add_information_id: data.data
                  });

                  if (idss === 1) {
                    _that.props.dispatch({
                      type: "add/getAuditVideo",
                      data: {
                        status: 1,
                        information_ids: [data.data]
                      }
                    });
                    _that.closeWindow();
                  }
                }
              }
            });
          }
        });
      } else {
        _that.props.dispatch({
          type: "add/addInformation",
          data: allForm,
          callback: data => {
            // this.closeWindow();
            setAdding(false, 0);
            if (data.code === 200) {
              this.submitTranscode(this.props.add.transcode_data, data.data, 2);
              message.success("保存成功!");
              _that.setState({
                add_information_id: data.data
              });

              if (idss === 1) {
                _that.props.dispatch({
                  type: "add/getAuditVideo",
                  data: {
                    status: 1,
                    information_ids: [data.data]
                  }
                });
                _that.closeWindow();
              }
            }
          }
        });
      }
    }
  };

  /*
    推送到微信
     */
  pushWeixin = () => {
    if (this.props.add.activeKey != "1") {
      message.error("只能推送文章");
      return;
    }
    let leftForm = this.props.getLeft();
    let rightForm = this.props.getRight();
    let allForm = {};

    // console.log(leftForm, rightForm)
    if (leftForm && rightForm) {
      Object.assign(allForm, leftForm, rightForm);
      if (!allForm["weixin_mpid"] || allForm["weixin_mpid"].length == 0) {
        message.error("请选择推送的公众号");
        return;
      }
      let push_data = {
        attachments: allForm["information_img"],
        title: allForm["information_title"],
        summary: allForm["intro"],
        content: allForm["content"],
        reporter: allForm["create_user"],
        mpid: allForm["weixin_mpid"]
      };
      let wx_url = this.props.add.configJson.weixinUrl;
      let hideConfig = message.loading("推送中...", 0);
      weixinPush(wx_url, push_data).then(res => {
        setTimeout(hideConfig, 100);
        if (res.data.code === 200) {
          message.success("推送成功");
        } else {
          message.error("推送失败");
        }
      });
    }
  };

  /**
   * 编辑  提交审核
   */
  toShenHe = () => {
    let leftForm = this.props.getLeft();
    let rightForm = this.props.getRight();
    let allForm = {};
    if (leftForm && rightForm) {
      Object.assign(allForm, leftForm, rightForm);

      allForm["information_id"] = this.props.id
        ? this.props.id
        : this.state.add_information_id;
      let _that = this;
      if (this.props.add.configJson.sensitivewordsSwitch) {
        validateSensitive({ content: allForm["content"] }).then(res => {
          if (res.data.code === 500) {
            confirm({
              title: "存在敏感词，确认继续保存吗",
              content: "敏感词：" + res.data.data,
              onOk() {
                _that.props.dispatch({
                  type: "add/editInformation",
                  data: allForm,
                  toShenHe: 1,
                  callback: code => {
                    if (code === 200) {
                      this.submitTranscode(
                        this.props.add.transcode_data,
                        allForm["information_id"],
                        2
                      );
                      _that.props.dispatch({
                        type: "add/getAuditVideo",
                        data: {
                          status: 1,
                          information_ids: [allForm["information_id"]]
                        }
                      });
                      _that.closeWindow();
                    }
                  }
                });
              },
              onCancel() { }
            });
          } else {
            _that.props.dispatch({
              type: "add/editInformation",
              data: allForm,
              toShenHe: 1,
              callback: code => {
                if (code === 200) {
                  this.submitTranscode(
                    this.props.add.transcode_data,
                    allForm["information_id"],
                    2
                  );
                  _that.props.dispatch({
                    type: "add/getAuditVideo",
                    data: {
                      status: 1,
                      information_ids: [allForm["information_id"]]
                    }
                  });
                  _that.closeWindow();
                }
              }
            });
          }
        });
      } else {
        _that.props.dispatch({
          type: "add/editInformation",
          data: allForm,
          toShenHe: 1,
          callback: code => {
            if (code === 200) {
              this.submitTranscode(
                this.props.add.transcode_data,
                allForm["information_id"],
                2
              );
              _that.props.dispatch({
                type: "add/getAuditVideo",
                data: {
                  status: 1,
                  information_ids: [allForm["information_id"]]
                }
              });
              _that.closeWindow();
            }
          }
        });
      }
    }
  };

  closeWindow = () => {
    // message.success('1秒后自动关闭页面~');
    // setTimeout(() => {
    //     window.close();
    // }, 1000);
  };

  /**
   * 修改
   */
  editSave = () => {
    let leftForm = this.props.getLeft();
    let rightForm = this.props.getRight();
    // console.log(rightForm, 'rightForm')
    let allForm = {};
    if (leftForm && rightForm) {
      Object.assign(allForm, leftForm, rightForm);
      allForm["information_id"] = this.props.id
        ? this.props.id
        : this.state.add_information_id;
      let _that = this;
      if (this.props.add.configJson.sensitivewordsSwitch) {
        validateSensitive({ content: allForm["content"] }).then(res => {
          if (res.data.code === 500) {
            confirm({
              title: "存在敏感词，确认继续保存吗",
              content: "敏感词：" + res.data.data,
              onOk() {
                _that.props.dispatch({
                  type: "add/editInformation",
                  data: allForm,
                  toShenHe: 0,
                  callback: code => {
                    if (code === 200) {
                      this.submitTranscode(
                        this.props.add.transcode_data,
                        allForm["information_id"],
                        2
                      );
                      message.success("保存成功!");
                      // this.closeWindow();
                    }
                  }
                });
              },
              onCancel() { }
            });
          } else {
            _that.props.dispatch({
              type: "add/editInformation",
              data: allForm,
              toShenHe: 0,
              callback: code => {
                if (code === 200) {
                  this.submitTranscode(
                    this.props.add.transcode_data,
                    allForm["information_id"],
                    2
                  );
                  message.success("保存成功!");
                  // this.closeWindow();
                }
              }
            });
          }
        });
      } else {
        _that.props.dispatch({
          type: "add/editInformation",
          data: allForm,
          toShenHe: 0,
          callback: code => {
            if (code === 200) {
              this.submitTranscode(
                this.props.add.transcode_data,
                allForm["information_id"],
                2
              );
              message.success("保存成功!");
              // this.closeWindow();
            }
          }
        });
      }

      // localStorage.setItem('treeSelectedKeys',extra.triggerNode.props.eventKey);
    }
  };

  //提交转码任务
  submitTranscode = (postData, id, type) => {
    if (postData && postData.length > 0) {
      postData.forEach(item => {
        item.article_id = item.video_id;
        item.type = 1;
        if (type == 2) {
          item.information_id = id;
        }
        if (type == 3) {
          item.theme_information_id = id;
        }
        transcode(item);
      });
      this.props.dispatch({
        type: "add/setTranscodeData",
        data: []
      });
    }
  };

  render() {
    let size = "large";
    return (
      <div className="Footer">
        {this.props.type === "edit" ? (
          <Button
            type="primary"
            size={size}
            onClick={throttle(this.toShenHe, 1000)}
          >
            ᠬᠢᠨᠠᠯᠲᠠ ᠳ᠋ᠤ᠌ ᠲᠤᠰᠢᠶᠠᠬᠤ
          </Button>
        ) : (
            <Button type="primary" onClick={() => this.submitForm(1)} size={size}>
              ᠡᠬᠡ ᠨᠣᠣᠷᠠᠭ ᠬᠠᠳᠠᠭᠠᠯᠠᠬᠤ
            </Button>
          )}

        {this.props.type === "edit" ? (
          <Button size={size} onClick={throttle(this.editSave, 1000)}>
            ᠬᠢᠨᠠᠯᠲᠠ ᠳ᠋ᠤ᠌ ᠲᠤᠰᠢᠶᠠᠬᠤ
          </Button>
        ) : (
            <Button size={size} onClick={throttle(this.submitForm, 1000)}>
              ᠡᠬᠡ ᠨᠣᠣᠷᠠᠭ ᠬᠠᠳᠠᠭᠠᠯᠠᠬᠤ
            </Button>
          )}

        {/* <Button size={size}>发布</Button> */}
        <Popconfirm
          className="FooterPop"
          placement="topLeft"
          icon={null}
          title="确认要重置吗?"
          onConfirm={this.reSet}
          onCancel={() => { }}
          okText="确定"
          cancelText="取消"
        >
          <Button size={size}>ᠳᠠᠬᠢᠵᠦ ᠲᠣᠬᠢᠷᠠᠭᠤᠯᠬᠤ</Button>
        </Popconfirm>

        <Popconfirm
          className="FooterPop"
          placement="topLeft"
          icon={null}
          title="请确认稿件已全部保存，返回列表界面?"
          onConfirm={this.confirm}
          onCancel={() => { }}
          okText="确定"
          cancelText="取消"
        >
          <Button size={size}> ᠬᠠᠭᠠᠬᠤ</Button>
        </Popconfirm>
        {this.props.add.configJson.weixinPushSwitch &&
          this.props.add.configJson.weixinUrl ? (
            <Popconfirm
              className="FooterPop"
              placement="topLeft"
              icon={null}
              title="请确认稿件已保存，确定推送?"
              onConfirm={this.pushWeixin}
              onCancel={() => { }}
              okText="确定"
              cancelText="取消"
            >
              <Button size={size}>ᠨᠡᠢᠲᠡᠯᠡᠬᠦ</Button>
            </Popconfirm>
          ) : (
            ""
          )}
      </div>
    );
  }
}
